package org.example;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Random;
import java.util.Scanner;

public class GroupChat {
    private static final String NAMESRV_ADDR = "124.71.28.51:9876";
    private static final String GROUP_CHAT_TOPIC = "IM_TOPIC";
    private final static FileProcess fileProcess = new FileProcess();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        String username = "hza";

        startProducer(scanner, username);


        startConsumer(username);

        System.out.println("Hello, " + username);
    }

    private static void startProducer(Scanner scanner, String username) {
        new Thread(() -> {
            try {
                DefaultMQProducer producer = new DefaultMQProducer("im_producer_group");
                producer.setNamesrvAddr(NAMESRV_ADDR);
                producer.start();

                while (true) {
                    String message = scanner.nextLine();
                    String[] parts = message.split(" ", 2);
                    if (parts.length != 2) {
                        System.err.println("请输入正确的命令格式！");
                    } else {
                        String key = parts[0];
                        String value = parts[1];
                        if (key.equals("TEXT")) {
                            value = username + ":" + value;
                            Message msg = new Message(GROUP_CHAT_TOPIC, "TEXT", value.getBytes());
                            producer.send(msg);
                        } else if (key.equals("FILE")) {
                            File file = new File(value);
                            if (file.exists() && file.isFile()) {
                                fileProcess.sendFile(producer, GROUP_CHAT_TOPIC, value);
                            } else {
                                System.err.println("指定的路径不存在或者不是一个文件！");
                            }
                        } else {
                            System.err.println("请输入正确的命令！");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }


    private static void startConsumer(String username) {
        new Thread(() -> {
            try {
                DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("im_consumer_group_" + username);
                consumer.setNamesrvAddr(NAMESRV_ADDR);
                consumer.subscribe(GROUP_CHAT_TOPIC, "*");

                // 注册消息处理器
                consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> {
                    for (MessageExt msg : msgs) {
                        String tag = msg.getTags();

                        // 根据标签进行不同的操作
                        if ("TEXT".equals(tag)) {
                            System.out.println(new String(msg.getBody()));
                        } else if ("FILE".equals(tag)) {
                            String outputDirectoryPath = "D:\\middleware_IM\\";
                            File directory = new File(outputDirectoryPath);
                            if (!(directory.isDirectory())) {
                                createDirectory(outputDirectoryPath);
                            }
                            fileProcess.receiverFile(outputDirectoryPath, msg);
                        } else {
                            // 处理其他标签的消息，以后可以补充
                            System.err.println("暂时无法处理该种类型的命令！");
                        }
                    }
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                });

                consumer.start();

                // 保持消费者线程一直运行，监听消息
                while (true) {
                    // 睡眠一段时间，防止过于频繁的轮询
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    private static void createDirectory(String outputDirectoryPath) {
        File directory = new File(outputDirectoryPath);
        if (!directory.exists()) {
            // 如果路径不存在，则创建文件夹
            boolean created = directory.mkdirs(); // mkdirs()方法会创建该路径及其父路径中不存在的文件夹
            if (created) {
                System.out.println("文件夹已创建！");
            } else {
                System.out.println("文件夹创建失败！");
            }
        } else {
            System.out.println("文件夹已存在！");
        }
    }

    private static void copyFile(File file, MessageExt msg) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            fos.write(msg.getBody());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
